<script setup lang="ts">
import { ref } from 'vue'

const carRef = ref();
const ICON_SIZE = 20;
const handleAdd = (e: Event) => {
  //创建icon
  const div = document.createElement('div');
  div.className = "circle";
  div.innerHTML = `<div class="circle-icon">+</div>`;
  // 点击按键并获取icon初始化位置
  const target = e.target as HTMLInputElement;
  const bntRect = target.getBoundingClientRect();
  // console.log(bntRect);
  const left: number = bntRect.left + bntRect.width / 2 - ICON_SIZE / 2;
  const top: number = bntRect.top - ICON_SIZE;
  div.style.setProperty('--left', `${left}px`);
  div.style.setProperty('--top', `${top}px`);
  // 获取icon的结束位置
  const carRect = carRef.value.getBoundingClientRect();
  const x = carRect.left + carRect.width / 2 - ICON_SIZE / 2 - left;
  const y = carRect.top - ICON_SIZE - top;
  div.style.setProperty('--x', `${x}px`);
  div.style.setProperty('--y', `${y}px`);
  // 动画结束时移除
  div.addEventListener('animationend', () => {
    div.remove();
  })
  // 添加icon到界面
  document.body.appendChild(div);
}
const count = ref(0)
</script>

<template>
  <div class="main">
    <ul>
      <li v-for="item in 10" class="main-item" :key="item">
        <span>商品{{ item }}</span>
        <button @click="handleAdd">+</button>
      </li>
    </ul>
    <div class="shop-car" ref="carRef">
      <img src="../assets/购物车.png" alt="" srcset="">
    </div>
    <!-- <div class="circle" style="--left:800px;--top:300px;--y:500px;--x:-200px;">
      <div class="circle-icon">+</div>
    </div> -->
</div>
</template>

<style>
.main {
  position: relative;
  width: 100vw;
  height: 100vh;
  margin: auto;
  /* border: 2px solid #ddd; */
}


.main-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
}

.shop-car {
  position: absolute;
  left: 20px;
  bottom: 20px;
  z-index: 10;
  width: 40px;
  height: 40px;
}

.shop-car>img {
  width: 100%;
}

.circle {
  position: fixed;
  width: 20px;
  height: 20px;
  line-height: 20px;
  border-radius: 20px;
  left: var(--left);
  top: var(--top);
  /* border: 2px solid #454545; */
}

.circle-icon {
  width: 100%;
  height: 100%;
  border-radius: 100%;
  background-color: #ff6c44;
  color: #fff;
  text-align: center;
}

@keyframes moveY {
  to {
    transform: translateY(var(--y));
  }
}

.circle {
  --duration: 0.8s;
  animation: moveY var(--duration) cubic-bezier(0.5, -0.5, 1, 1);
}

@keyframes moveX {
  to {
    transform: translateX(var(--x));
  }
}

.circle-icon {
  animation: moveX var(--duration) linear;
}
</style>
